Write to a Sentence to a File with C Program

07-11-17 Course- C

This program stores a sentence entered by user in a file.


#include <stdio.h>
#include <stdlib.h>  /* For exit() function */
int main()
{
   char c[1000];
   FILE *fptr;
   fptr=fopen("program.txt","w");
   if(fptr==NULL){
      printf("Error!");
      exit(1);
   }
   printf("Enter a sentence:\n");
   gets(c);
   fprintf(fptr,"%s",c);
   fclose(fptr);
   return 0;
}

Output


Enter sentence: 
I am awesome and so are files. 

After termination of this program, you can see a text file program.txt created in the same location where this program is located. If you open and see the content, you can see the sentence: I am awesome and so are files.

In this program, a file is opened using opening mode "w". In this mode, if the file exists, its contents are overwritten and if the file does not exist, it will be created. Then, user is asked to enter a sentence. This sentence will be stored in file program.txt using fprintf() function.